<?php
function processgCart ($gParams) {
	if($_SESSION["tempCart"]) {
		
		//This information is located by logging into your sellers account.
		$merchant_id = $gParams['gID'];
		$merchant_key = $gParams['gKey'];
		
		//Create a new cart object and setup its basic options
		$gCart = new gCart($merchant_id, $merchant_key);
		$gTaxRule = new gTaxRule($gParams['gTaxRate'],'ALL');
		$gTaxRule->setShippingTaxed($gParams['gTaxShipping']);
		$gTaxTable = new gTaxTable('Default',array($gTaxRule),'default');
		$gAltTaxTable = new gTaxTable('tax_exempt','','alternate','true');
		$gCart->setDefaultTaxTable($gTaxTable);
		$gCart->setAlternateTaxTables(array($gAltTaxTable));
		
		//Shipping Options
		$gShippingOption1 = new gShippingOption('20.00','UPS','REGULAR_PICKUP','Ground','3.00');
		$gShippingOption2 = new gShippingOption('40.00','UPS','REGULAR_PICKUP','3 Day Select','3.00');
		$gShippingOption3 = new gShippingOption('60.00','UPS','REGULAR_PICKUP','Next Day Air','3.00');
		$gShippingOption = array($gShippingOption1,$gShippingOption2,$gShippingOption3);
		$gShippingPackage = new gShippingPackage($gParams['gShipID'],$gParams['gZipCode'], $gParams['gCity'], $gParams['gState'],'US','17','17','17');
		$gShipping = array(new gShipping('Standard','10','carrier-calculated-shipping',$gShippingOption, $gShippingPackage));
		

		
		
		//Add the items from the tempCart into the cart being passed to Google. 
		foreach($_SESSION["tempCart"] as $item) {
			
			//Check if item if tax-exempt.
			if ($item['taxstatus'] != 'Yes') {
				$gCart->addItem($item['name'],$item['description'],$item['quantity'],$item['price'],$item['weight']);
				} else
					$gCart->addItem($item['name'],$item['description'],$item['quantity'],$item['price'],$item['weight'],'tax_exempt');
			
			//Check if all items in the cart are eligible for free shipping.
			if ($item['freeship'] != 'Yes')
				$charge = true;
			}
		
		//All Items in the cart are eligible for free shipping.
		if($charge) $gCart->setShipping($gShipping);
		
		//Add all your discounts by calling the functions created in the discount file
		//addTieredDiscount('.1,.15,.2','11,23,47','wine','Bulk Discount');
		//addAgeFee('3.50','wine','Age Verification','Your shipment contains wine and requires the UPS driver to check identification.');

		
		//Add the discounts into the cart being passed to Google
		$_SESSION["gTotalDiscounts"] = 0;
		foreach($_SESSION["gDiscounts"] as $item) {
			$gCart->addItem($item['name'],$item['description'],$item['quantity'],$item['price'],$item['weight']);
			$_SESSION["gTotalDiscounts"] += $item['price'];
			}
		
		//Add the fees into the cart being passed to Google
		
		$_SESSION["gTotalFees"] = 0;
		foreach($_SESSION["gFees"] as $item) {
			$gCart->addItem($item['name'],$item['description'],$item['quantity'],$item['price'],$item['weight']);
			$_SESSION["gTotalFees"] += $item['price'];
			}
		//echo $gCart->getCart();	
		return $gCart; 
	}
	return false;
}

function getButton($gCart,$size) {
	//Generate the checkout button
	$gButton = new gButton($gCart,$size);
	return $gButton->getPostButton();
}

function getOutput($gParams,$gCart) {
	global $modx;
	
	//Set default templates
	if(!$gParams['gCartTpl']) $gParams['gCartTpl'] = '[+gWrap+]
								<p><a href="[+gClearCartURL+]">Clear Cart</a></p>
								<p>Total Items: [+gTotalItems+]</p>
								<p>Subtotal: $[+gSubtotal+]</p>
								<p>Discount: $[+gDiscount+]</p>
								[+gButton+]';
								
	
	if(!$gParams['gAjaxTpl']) $gParams['gAjaxTpl'] = '<div id="highlight">[+gAjax+]</div>';
	if(!$gParams['gEmptyTpl']) $gParams['gEmptyTpl'] = '<div id="minicart"><h1>Your Cart</h1><p>Your cart is empty.</p></div>';
	
	if(!$gParams['gItemTpl']) $gParams['gItemTpl'] = '<p>
									<a href="[+gClearItemURL+]">
										<img alt="Remove Item" class="right" height="11" src="http://www.cmssandbox.com/MODx095/assets/images/list_remove_btn.gif" title="Remove Item" width="11" />
									</a>
									<a href="[+gItemURL+]">[+gName+]</a><br />
									<strong>Qty: [+gQuantity+]</strong>
								</p>';
				
	//Check if the cart is empty
	if(!$_SESSION["tempCart"]) return $gParams['gEmptyTpl'];

	//Output the templated items
	foreach($_SESSION["tempCart"] as $item) {
			$output = str_replace('[+gName+]',$item['name'],$gParams['gItemTpl']);
			$output = str_replace('[+gSKU+]',$item['sku'],$output);
			$output = str_replace('[+gAlias+]',$item['alias'],$output);
			$output = str_replace('[+gQuantity+]',$item['quantity'],$output);
			$output = str_replace('[+gItemURL+]',$item['sku'],$output);
			$output = str_replace('[+gItemTotal+]',number_format($item['price']*$item['quantity'],2),$output);
			$output = str_replace('[+gClearItemURL+]',$modx->makeURL($modx->documentIdentifier).'&amp;clearItem='.$item['sku'],$output);
			$output = str_replace('[+gIncrementURL+]',$modx->makeURL($modx->documentIdentifier).'&amp;increment='.$item['sku'],$output);
			$output = str_replace('[+gDecrementURL+]',$modx->makeURL($modx->documentIdentifier).'&amp;decrement='.$item['sku'],$output);
			$output = str_replace('[+gPrice+]',$item['price'],$output);
			$finalOutput .= $output;
	}
	
	//Output the items wrapped inside the cart
	$estimatedTax = $gParams['gTaxRate'] * $_SESSION["gCartInfo"]['subtotal'];
	$finalOutput = str_replace('[+gWrap+]',$finalOutput,$gParams['gCartTpl']);
	$finalOutput = str_replace('[+gClearCartURL+]',$modx->makeURL($modx->documentIdentifier).'&amp;clearCart=1',$finalOutput);
	$finalOutput = str_replace('[+gTotalItems+]',$_SESSION["gCartInfo"]['quantity'],$finalOutput);
	$finalOutput = str_replace('[+gWeight+]',$_SESSION["gCartInfo"]['weight'],$finalOutput);
	$finalOutput = str_replace('[+gError+]',$_SESSION["error"],$finalOutput);
	$finalOutput = str_replace('[+gSubtotal+]',number_format($_SESSION["gCartInfo"]['subtotal'],2),$finalOutput);
	$finalOutput = str_replace('[+gEstimatedTax+]',number_format($estimatedTax,2),$finalOutput);
	$finalOutput = str_replace('[+gDiscount+]',number_format($_SESSION["gTotalDiscounts"],2),$finalOutput);
	$finalOutput = str_replace('[+gEncodedCart+]',$gCart->getEncodedCart(),$finalOutput);
	$finalOutput = str_replace('[+gEncodedSig+]',$gCart->getEncodedSignature(),$finalOutput);
	if($_POST['gName']) $finalOutput = str_replace('[+gAjax+]',$finalOutput,$gParams['gAjaxTpl']);

	return $finalOutput;
}


function getPayPal($gParams) {
	global $modx;
	
	//Discounts and Fees
	//addTieredDiscount('.1,.15,.2','11,23,47','wine','Bulk Discount');
	//addAgeFee('3.50','wine','Age Verification','Your shipment contains wine and requires the UPS driver to check identification.');
	
	//Add the discounts into the cart being passed to PayPal
	$_SESSION["gTotalDiscounts"] = 0;
	foreach($_SESSION["gDiscounts"] as $item) {
		$_SESSION["gTotalDiscounts"] += $item['price'];
		}
		
	//Add Shipping Fees from UPS
	if($_SESSION["gCartInfo"]['weight'] != 0) {
		$rate = new Ups;
		$rate->upsProduct($_SESSION['gCartInfo']['shipMethod']); // See upsProduct() function for codes
		$rate->origin($gParams['gZipCode'], "US"); // Use ISO country codes!
		$rate->dest($_SESSION['gCartInfo']['shipZip'], "US"); // Use ISO country codes!
		$rate->rate("RDP"); // See the rate() function for codes
		$rate->container("CP"); // See the container() function for codes
		$rate->weight($_SESSION["gCartInfo"]['weight']);
		$rate->rescom("RES"); // See the rescom() function for codes
		$quote = $rate->getQuote() + $gParams['upsHandling'];
		addItem($quote,'shipfee','Shipping and Handling - '. $_SESSION['gCartInfo']['shipMethod'],'shipping');
		} else unset($_SESSION["gFees"]['shipfee']);
		
		
		//Set default templates
	if(!$gParams['gCartTpl']) $gParams['gCartTpl'] = '[+gWrap+]
								<p><a href="[+gClearCartURL+]">Clear Cart</a></p>
								<p>Total Items: [+gTotalItems+]</p>
								<p>Subtotal: $[+gSubtotal+]</p>
								<p>Discount: $[+gDiscount+]</p>
								[+gButton+]';
								
	
	if(!$gParams['gAjaxTpl']) $gParams['gAjaxTpl'] = '<div id="highlight">[+gAjax+]</div>';
	if(!$gParams['gEmptyTpl']) $gParams['gEmptyTpl'] = '<div id="minicart"><h1>Your Cart</h1><p>Your cart is empty.</p></div>';
	
	if(!$gParams['gItemTpl']) $gParams['gItemTpl'] = '<p>
									<a href="[+gClearItemURL+]">
										<img alt="Remove Item" class="right" height="11" src="http://www.cmssandbox.com/MODx095/assets/images/list_remove_btn.gif" title="Remove Item" width="11" />
									</a>
									<a href="[+gItemURL+]">[+gName+]</a><br />
									<strong>Qty: [+gQuantity+]</strong>
								</p>';
	
	$tempCount = 1;
	$foxyTpl = '  
				<input name="item_name_[+tempCount+]" type="hidden" value="[+gName+]" />
				<input name="amount_[+tempCount+]" type="hidden" value="[+gPrice+]" />
				<input name="quantity_[+tempCount+]" type="hidden" value="[+gQuantity+]" />';
				
	if($_SESSION['gCartInfo']['shipZip'])
		$foxyWrap = ' <div id="paypal" class="gOptionItem">
						<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
						  <fieldset>
							<input name="cmd" type="hidden" value="_cart" />
							<input name="upload" type="hidden" value="1" />
							<input name="business" type="hidden" value="'.$gParams['pID'].'" />
							<input name="return" type="hidden" value="https://secure28.inmotionhosting.com/~bluesk5/received-payment" />
							<input name="cpp_header_image" type="hidden" value="https://secure28.inmotionhosting.com/~bluesk5/assets/images/paypal-branding.jpg" />
							<input name="image_url" type="hidden" value="https://secure28.inmotionhosting.com/~bluesk5/assets/images/paypal-branding-all.jpg" />
							[+gWrap+]
						<input type="image" name="PayPal Checkout" alt="Checkout and Pay" src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" />
						  </fieldset>
						</form>
					  </div>';
		else 
			$foxyWrap = '<div class="gOptionItem">
							<form action="'.$modx->makeURL($modx->documentIdentifier).'" method="post">
							  <fieldset>
								   <p><label for="shipZip" class="wide"><strong>Shipping Zipcode:</strong></label>
											<input maxlength="5" type="text" name="shipZip" id="shipZip" class="field" value="" />
									</p>
								   <p>
									<label for="shipMethod" class="wide">Shipping Method:</label>
									<select name="shipMethod" id="shipMethod" class="combo">
									  <option value="GND">
										Ground
									  </option>
									  <option value="3DS">
										3 Day Select
									  </option>
									  <option value="2DA">
										2 Day Air
									  </option>
									</select>
								  </p>
								<p><input type="submit" value="Calculate Shipping" /></p>
							  </fieldset>
							</form>
						  </div>';
				
	//Check if the cart is empty
	if(!$_SESSION["tempCart"]) return $gParams['gEmptyTpl'];

	//Output the templated items
	foreach($_SESSION["tempCart"] as $item) {
			$output = str_replace('[+gName+]',$item['name'],$gParams['gItemTpl']);
			$output = str_replace('[+gSKU+]',$item['sku'],$output);
			$output = str_replace('[+gAlias+]',$item['alias'],$output);
			$output = str_replace('[+gQuantity+]',$item['quantity'],$output);
			$output = str_replace('[+gItemURL+]',$item['sku'],$output);
			$output = str_replace('[+gItemTotal+]',number_format($item['price']*$item['quantity'],2),$output);
			$output = str_replace('[+gClearItemURL+]',$modx->makeURL($modx->documentIdentifier).'&amp;clearItem='.$item['sku'],$output);
			$output = str_replace('[+gIncrementURL+]',$modx->makeURL($modx->documentIdentifier).'&amp;increment='.$item['sku'],$output);
			$output = str_replace('[+gDecrementURL+]',$modx->makeURL($modx->documentIdentifier).'&amp;decrement='.$item['sku'],$output);
			$output = str_replace('[+gPrice+]',$item['price'],$output);
			$cartOutput .= $output;
			
			$output = str_replace('[+gName+]',$item['name'],$foxyTpl);
			$output = str_replace('[+gSKU+]',$item['sku'],$output);
			$output = str_replace('[+gWeight+]',$item['weight'],$output);
			$output = str_replace('[+gQuantity+]',$item['quantity'],$output);
			$output = str_replace('[+gPrice+]',$item['price'] * (1 - $_SESSION["gDiscountRate"]),$output);
			$output = str_replace('[+gDiscount+]',$item['discount'],$output);
			$output = str_replace('[+tempCount+]',"$tempCount",$output);
			$buttonOutput .= $output;
			$tempCount++;
	}
	
	//Output the items wrapped inside the cart
	$estimatedTax = $gParams['gTaxRate'] * $_SESSION["gCartInfo"]['subtotal'];
	$finalOutput = str_replace('[+gWrap+]',$cartOutput,$gParams['gCartTpl']);
	$finalOutput = str_replace('[+gClearCartURL+]',$modx->makeURL($modx->documentIdentifier).'&amp;clearCart=1',$finalOutput);
	$finalOutput = str_replace('[+gTotalItems+]',$_SESSION["gCartInfo"]['quantity'],$finalOutput);
	$finalOutput = str_replace('[+gWeight+]',$_SESSION["gCartInfo"]['weight'],$finalOutput);
	$finalOutput = str_replace('[+gError+]',$_SESSION["error"],$finalOutput);
	$finalOutput = str_replace('[+gSubtotal+]',number_format($_SESSION["gCartInfo"]['subtotal'],2),$finalOutput);
	$finalOutput = str_replace('[+gEstimatedTax+]',number_format($estimatedTax,2),$finalOutput);
	$finalOutput = str_replace('[+gDiscount+]',number_format($_SESSION["gTotalDiscounts"],2),$finalOutput);
	$finalOutput = str_replace('[+gShipping+]',number_format($quote,2),$finalOutput);
	if($_POST['gName']) $finalOutput = str_replace('[+gAjax+]',$finalOutput,$gParams['gAjaxTpl']);

	foreach($_SESSION["gFees"] as $item) {
			$output = str_replace('[+gName+]',$item['name'],$foxyTpl);
			$output = str_replace('[+gSKU+]',$item['sku'],$output);
			$output = str_replace('[+gWeight+]',$item['weight'],$output);
			$output = str_replace('[+gQuantity+]',$item['quantity'],$output);
			$output = str_replace('[+gPrice+]',$item['price'],$output);
			$output = str_replace('[+gDiscount+]',"additional",$output);
			$output = str_replace('[+tempCount+]',"$tempCount",$output);
			$buttonOutput .= $output;
			$tempCount++;
	}

	//Output the items wrapped inside the cart
	$buttonOutput = str_replace('[+gWrap+]',$buttonOutput,$foxyWrap);
	if($_SESSION["gCartInfo"]['weight'] <= 150) 
		$finalOutput = str_replace('[+gButton+]',$buttonOutput,$finalOutput);
		else $finalOutput = str_replace('[+gButton+]','<p>Oops, your cart is too heavy.  Please remove an item and <a href="checkout">update</a> your cart</p>',$finalOutput);

	return $finalOutput;
}
?>